<template>
  <div class="interview-records">
    <a-card title="面试记录" :bordered="false" class="records-card">
      <template #title>
        <div class="card-title">
          <a-button type="link" class="back-button" @click="router.back()">
            <arrow-left-outlined />
          </a-button>
          <span>面试记录</span>
        </div>
      </template>
      <template #extra>
        <div class="filter-actions">
          <a-input-search
            v-model:value="searchText"
            placeholder="搜索应聘者姓名"
            style="width: 200px; margin-right: 16px"
            @search="handleSearch"
          />
          <a-select
            v-model:value="filterPosition"
            placeholder="应聘岗位"
            style="width: 150px"
            @change="handleFilterChange"
          >
            <a-select-option value="">全部岗位</a-select-option>
            <a-select-option value="java后端开发">Java后端开发</a-select-option>
            <a-select-option value="前端开发">前端开发</a-select-option>
            <a-select-option value="算法工程师">算法工程师</a-select-option>
            <a-select-option value="测试工程师">测试工程师</a-select-option>
            <a-select-option value="产品经理">产品经理</a-select-option>
          </a-select>
        </div>
      </template>

      <!-- 面试记录表格 -->
      <a-table
        :columns="columns"
        :data-source="filteredRecords"
        :loading="loading"
        :pagination="{ pageSize: 10 }"
        :row-key="(record) => record.fullProcessInterviewId"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'candidate'">
            <div>
              <div style="font-weight: 500">{{ record.userName }}</div>
              <div style="font-size: 12px; color: #999">{{ record.userEmail }}</div>
            </div>
          </template>

          <template v-if="column.key === 'score'">
            <span
              :style="`color: ${
                record.totalScore >= 85
                  ? '#52c41a'
                  : record.totalScore >= 70
                  ? '#1890ff'
                  : '#faad14'
              }; font-weight: 500;`"
            >
              {{ record.totalScore }}分
            </span>
          </template>

          <template v-if="column.key === 'personScore'">
            <span>{{ record.personScore ?? '-' }}</span>
          </template>
          <template v-if="column.key === 'personComment'">
            <span>{{ record.personComment ?? '-' }}</span>
          </template>

          <template v-if="column.key === 'action'">
            <div class="action-buttons">
              <a-dropdown>
                <template #overlay>
                  <a-menu>
                    <a-menu-item key="resume" @click="viewResume(record)">查看简历</a-menu-item>
                    <a-menu-item key="resumeAnalysis" @click="goToResumeAnalysis(record)"
                      >简历分析
                    </a-menu-item>
                    <a-menu-item key="writtenTest" @click="goToWrittenTest(record)"
                      >笔试分析
                    </a-menu-item>
                    <a-menu-item key="techInterview" @click="goToTechInterview(record)"
                      >技术面分析
                    </a-menu-item>
                    <a-menu-item key="hrInterview" @click="goToHrInterview(record)"
                      >HR面分析
                    </a-menu-item>
                    <a-menu-item key="fullProcess" @click="goToFullProcess(record)"
                      >全流程分析
                    </a-menu-item>
                  </a-menu>
                </template>
                <a-button type="link">
                  查看详情
                  <down-outlined />
                </a-button>
              </a-dropdown>
              <a-button type="default" @click="openScoringModal(record)">
                {{ record.personScore != null ? '修改评分' : '人工评分' }}
              </a-button>
              <a-button type="primary" @click="approveInterview(record)">安排线上面试</a-button>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 安排线上面试弹窗 -->
    <a-modal
      v-model:visible="interviewModalVisible"
      title="安排线上面试"
      @ok="submitInterviewArrangement"
      :confirmLoading="interviewLoading"
    >
      <template v-if="selectedCandidate">
        <a-form :model="interviewForm" layout="vertical">
          <div class="candidate-info-header">
            <h3>{{ selectedCandidate?.userName }}</h3>
            <p>{{ selectedCandidate?.userEmail }}</p>
            <p>应聘岗位：{{ selectedCandidate?.position }}</p>
          </div>

          <a-form-item label="面试时间" required>
            <a-date-picker
              v-model:value="interviewForm.date"
              style="width: 48%; margin-right: 4%"
              placeholder="选择日期"
            />
            <a-time-picker
              v-model:value="interviewForm.time"
              style="width: 48%"
              format="HH:mm"
              placeholder="选择时间"
            />
          </a-form-item>

          <a-form-item label="腾讯会议码" required>
            <a-input v-model:value="interviewForm.txMeetingCode" placeholder="请输入腾讯会议码" />
          </a-form-item>

          <a-form-item label="面试官">
            <a-input v-model:value="interviewForm.interviewer" placeholder="请输入面试官姓名" />
          </a-form-item>

          <a-form-item label="备注">
            <a-textarea
              v-model:value="interviewForm.remarks"
              :rows="4"
              placeholder="请输入备注信息（可选）"
            />
          </a-form-item>
        </a-form>
      </template>
    </a-modal>

    <!-- 人工评分弹窗 -->
    <a-modal
      v-model:visible="scoringModalVisible"
      :title="selectedRecordForScoring?.personScore != null ? '修改评分' : '人工评分'"
      @ok="handleScoringSubmit"
      :confirmLoading="scoringLoading"
    >
      <a-form :model="scoringForm" layout="vertical">
        <a-form-item label="评分" required>
          <a-input-number
            v-model:value="scoringForm.personScore"
            :min="0"
            :max="100"
            style="width: 100%"
            placeholder="请输入分数 (0-100)"
          />
        </a-form-item>
        <a-form-item label="评价" required>
          <a-textarea
            v-model:value="scoringForm.personComment"
            :rows="4"
            placeholder="请输入评价"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { ArrowLeftOutlined, DownOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import {
  getFullProcessInterviewListWithCompanyUsingGet, personScoringAndCommentUsingPost,
  sendOnlineInterviewInviteUsingPost
} from '@/api/commonController'
import { useLoginUserStore } from '@/stores/useLoginUserstore'

const router = useRouter()
const userStore = useLoginUserStore()

// 表格列定义
const columns = [
  {
    title: '应聘者',
    dataIndex: 'userName',
    key: 'candidate',
    width: '20%',
  },
  {
    title: '应聘岗位',
    dataIndex: 'position',
    key: 'position',
    width: '10%',
  },
  {
    title: '模拟面试时间',
    dataIndex: 'interviewTime',
    key: 'interviewTime',
    width: '20%',
    sorter: (a, b) => Number(new Date(a.interviewTime)) - Number(new Date(b.interviewTime)),
    customRender: ({ text }) => {
      const date = new Date(text)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
      })
    },
  },
  {
    title: '综合评分',
    dataIndex: 'totalScore',
    key: 'score',
    width: '10%',
    sorter: (a, b) => a.totalScore - b.totalScore,
  },
  {
    title: '人工评分',
    dataIndex: 'personScore',
    key: 'personScore',
    width: '10%'
  },
  {
    title: '人工评价',
    dataIndex: 'personComment',
    key: 'personComment',
    width: '15%'
  },
  {
    title: '操作',
    key: 'action',
    width: '25%'
  }
]

// 面试记录数据 - 从API获取
const interviewRecords = ref([])

// 筛选和搜索状态
const searchText = ref('')
const filterPosition = ref('')
const loading = ref(false)

// 安排面试模态框状态
const interviewModalVisible = ref(false)
const interviewLoading = ref(false)
const selectedCandidate = ref(null)

// 人工评分模态框状态
const scoringModalVisible = ref(false)
const scoringLoading = ref(false)
const selectedRecordForScoring = ref(null)
const scoringForm = ref({
  personScore: null as number | null,
  personComment: ''
})

// 面试安排表单
const interviewForm = ref({
  date: null,
  time: null,
  txMeetingCode: '',
  interviewer: '',
  remarks: '',
})

// 筛选后的记录
const filteredRecords = computed(() => {
  return interviewRecords.value.filter((record) => {
    // 搜索名称或邮箱
    const searchMatch =
      record.userName.toLowerCase().includes(searchText.value.toLowerCase()) ||
      record.userEmail.toLowerCase().includes(searchText.value.toLowerCase())

    // 筛选岗位
    const positionMatch = filterPosition.value ? record.position === filterPosition.value : true

    return searchMatch && positionMatch
  })
})

// 处理搜索
const handleSearch = () => {
  // 使用本地筛选，已通过computed实现
}

// 处理筛选变化
const handleFilterChange = () => {
  // 使用本地筛选，已通过computed实现
}

// 查看简历
const viewResume = (record) => {
  const link = document.createElement('a')
  link.href = record.resumeUrl
  link.download = 'resume.pdf' // 设置下载的文件名（带扩展名）
  link.target = '_blank' // 可选：在新标签页打开
  link.click()
}

// 查看简历分析
const goToResumeAnalysis = (record) => {
  router.push({
    path: '/api/analyze/resume',
    query: { id: record.resumeId },
  })
}

// 查看笔试分析
const goToWrittenTest = (record) => {
  router.push({
    path: '/api/written/analyze',
    query: { examId: record.examId },
  })
}

// 查看技术面分析
const goToTechInterview = (record) => {
  router.push({
    path: '/api/tec/analyze',
    query: { id: record.aiInterviewId },
  })
}

// 查看HR面分析
const goToHrInterview = (record) => {
  router.push({
    path: '/api/hr/interview/analyze',
    query: { id: record.hrInterviewId },
  })
}

// 查看全流程分析
const goToFullProcess = (record) => {
  router.push({
    path: '/api/full/interview/analyze',
    query: { id: record.fullProcessInterviewId },
  })
}

// 安排线上面试
const approveInterview = (record) => {
  selectedCandidate.value = record

  // 重置表单
  interviewForm.value = {
    date: null,
    time: null,
    txMeetingCode: '',
    interviewer: '',
    remarks: '',
  }

  interviewModalVisible.value = true
}

// 打开评分弹窗
const openScoringModal = (record: any) => {
  selectedRecordForScoring.value = record
  scoringForm.value.personScore = record.personScore ?? null
  scoringForm.value.personComment = record.personComment ?? ''
  scoringModalVisible.value = true
}

// 提交人工评分
const handleScoringSubmit = async () => {
  if (
    scoringForm.value.personScore === null ||
    scoringForm.value.personScore < 0 ||
    scoringForm.value.personScore > 100
  ) {
    message.error('请输入0-100之间的有效分数')
    return
  }
  if (!scoringForm.value.personComment?.trim()) {
    message.error('请输入评价内容')
    return
  }

  scoringLoading.value = true
  try {
    const res = await personScoringAndCommentUsingPost({
      fullProcessInterviewId: selectedRecordForScoring.value.fullProcessInterviewId,
      personScore: scoringForm.value.personScore,
      personComment: scoringForm.value.personComment
    })

    if (res.data) {
      message.success('评分成功')
      scoringModalVisible.value = false
      await fetchFullProcessInterviewList() // Refresh data
    } else {
      message.error(res.message || '评分失败')
    }
  } catch (e) {
    console.error(e)
    message.error('评分出错，请稍后重试')
  } finally {
    scoringLoading.value = false
  }
}

// 提交面试安排
const submitInterviewArrangement = async () => {
  // 表单验证
  if (!interviewForm.value.date) {
    message.error('请选择面试日期')
    return
  }

  if (!interviewForm.value.time) {
    message.error('请选择面试时间')
    return
  }

  if (!interviewForm.value.txMeetingCode) {
    message.error('请输入腾讯会议码')
    return
  }

  interviewLoading.value = true

  // 组合日期和时间为一个完整的日期时间对象
  const combinedDateTime = new Date(interviewForm.value.date)
  const timeDate = new Date(interviewForm.value.time)

  combinedDateTime.setHours(timeDate.getHours(), timeDate.getMinutes(), timeDate.getSeconds())

  function formatDateToBackend(date) {
    const pad = n => String(n).padStart(2, '0')
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
      `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
  }

  const submitData = {
    ...selectedCandidate.value,
    interviewTime: formatDateToBackend(combinedDateTime), // "2025-06-18 11:00:00"
    txMeetingCode: interviewForm.value.txMeetingCode,
    interviewerName: interviewForm.value.interviewer,
    notes: interviewForm.value.remarks,
  }

  // 调用API
  const data = await sendOnlineInterviewInviteUsingPost(submitData)
  if (data.data) {
    message.success('已成功发送面试邀请')
    //重新获取面试记录
    await fetchFullProcessInterviewList()
  } else {
    message.error('发送面试邀请失败')
  }
  //关闭弹窗
  interviewModalVisible.value = false
  //关闭按钮加载
  interviewLoading.value = false
}

//获取全流程面试记录（已通过并且未邀请的)
const fetchFullProcessInterviewList = async () => {
  const company = userStore.loginUser?.company

  loading.value = true

  if (company) {
    try {
      const response = await getFullProcessInterviewListWithCompanyUsingGet({
        company: company,
      })

      if (response.data) {
        interviewRecords.value = response.data as any
      } else {
        message.error('获取面试记录失败')
      }
    } catch (error) {
      console.error('获取面试记录出错:', error)
      message.error('获取面试记录出错')
    }
  }

  loading.value = false
}
/**
 * 人工评分
 */
const personScoringAndComment = async () => {
  const res = personScoringAndCommentUsingPost({
    fullProcessInterviewId: "",
    personComment: "",
    personScore: ""
  } as any)
}

// 组件挂载时获取数据
onMounted(async () => {
  //获取全流程面试记录（已通过并且未邀请的)
  await fetchFullProcessInterviewList()
})
</script>

<style scoped>
.interview-records {
  padding: 24px;
  background: #f0f2f5;
  min-height: calc(100vh - 64px);
}

.records-card {
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.card-title {
  display: flex;
  align-items: center;
}

.back-button {
  margin-right: 12px;
  font-size: 18px;
  padding: 0;
  color: #1890ff;
}

.filter-actions {
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

/* 面试安排弹窗样式 */
.candidate-info-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.candidate-info-header h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
}

.candidate-info-header p {
  margin: 0 0 4px 0;
  color: #666;
}
</style>
